package org.example.tialsproject.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.tialsproject.pojo.ResponseResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class SessionController {
    /*获取指定Cookie*/
    @GetMapping("/c1")
    public ResponseResult c1(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String cookieName = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("login")) {
                System.out.println(cookie.getValue());
                cookieName = cookie.getValue();
            }
        }
        return ResponseResult.success(cookieName);
    }

    /*设置Cookie*/
    @GetMapping("/c2")
    public ResponseResult c2(HttpServletResponse response) {
        response.addCookie(new Cookie("login", "TaoPinQi"));
        return ResponseResult.success("Cookie设置成功");
    }

    @GetMapping("/s1")
    public ResponseResult s1(HttpSession session) {
        session.setAttribute("login", "TaoPinQi");
        return ResponseResult.success("session设置成功");
    }

    @GetMapping("/s2")
    public ResponseResult s2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object login = session.getAttribute("login");
        return ResponseResult.success(login);
    }

    /*生成JWT*/
    @GetMapping("/getjwt")
    public ResponseResult getJwt() {
        /*往hashMap中添加键值对*/
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", "TaoPinQi");
        claims.put("id", 1);
        // 设置签名算法以及自定义内容(载荷)以及令牌有效期，返回一个字符串的jwt
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, "TaoPinQi").setClaims(claims).setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)).compact();
        return ResponseResult.success(jwt);
    }

    /*解析JWT*/
    @GetMapping("/renderjwt")
    public ResponseResult renderJwt() {
        Claims claims = Jwts.parser().setSigningKey("TaoPinQi").parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlck5hbWUiOiJUYW9QaW5RaSIsImV4cCI6MTcxNzI4OTU1NH0.PvA2Gw8TJ1t5pscX7FIfV6yImRWnOqBbwFGkHmd_Lf4").getBody();
        return ResponseResult.success(claims);
    }

}
